'use strict';

const Controller = require('egg').Controller;

class CityController extends Controller {
    // 新建 编辑
    async edit() {
        const { ctx, app } = this
        const { id, name, sort, status } = ctx.request.body
        ctx.validate({
            name: {
                type: 'string', required: true, desc: '城市名称'
            }
        })
        let list
        if (id == 0) { //新增
            list = await app.model.City.findOne({
                where: {
                    name
                }
            })
            if (list) {
                ctx.throw(400, '城市名称已存在!')
            }
            list = await app.model.City.create({
                name, sort: sort || 1, status
            })
        } else { //编辑
            list = await app.model.City.findByPk(id)
            if (!list) {
                ctx.throw(400, '数据不存在')
            }
            list = await list.update({ name, sort, status })
        }
        ctx.apiSuccess(list)
    }
    // 列表
    async list() {
        const { ctx, app } = this
        const { name } = ctx.request.body
        const Op = app.Sequelize.Op;
        let where = {}, list
        if (name !== '' && name != undefined) {
            where.name = {
                [Op.like]: '%' + name + '%'
            }
        }
        list = await app.model.City.findAndCountAll({
            where: {
                ...where,
                status: '1'
            },
            order: [
                ['sort', 'DESC'],
            ]

        })
        ctx.apiSuccess(list)
    }
    //删除
    async del(){
        const {ctx,app}=this
        const id=ctx.params.id
     
        const list=await app.model.City.findByPk(id)
        if(!list){
            ctx.throw(400,'数据不存在')
        }
        list.destroy()
        ctx.apiSuccess('删除成功')
    }

}

module.exports = CityController;
